from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from PySide6.QtWidgets import QLabel, QComboBox, QPushButton
from enums.ZhButtonType import ZhButtonType
from enums.ButtonType import ButtonType
import time
from enums.WidgetType import WidgetType
from ..ScriptInput import ScriptInput
from ..ScriptTimeInput import ScriptTimeInput
from util.Mouse import MouseUtil


class LongPressPos(ScriptWidget):
    def __init__(self, initType=None):
        super().__init__(WidgetType.LONG_PRESS_POS)

        self.pressTime = 0
        self.initType = initType

        self.labTitle = QLabel('长按:', self)
        self.labTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        # x
        self.inputX = ScriptInput(self, 'x')
        self.addWidget(self.inputX)

        # y
        self.inputY = ScriptInput(self, 'y')
        self.addWidget(self.inputY)

        self.inputX.text = 0
        self.inputY.text = 0

        # buttonType
        self.comButtonType = QComboBox(self)
        self.comButtonType.addItems(ZhButtonType.values())
        self.comButtonType.setCurrentText(ZhButtonType.values()[0])
        self.addWidget(self.comButtonType)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        self.inputTime = ScriptTimeInput(self, '时间')
        self.addWidget(self.inputTime)

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('模拟')
        self.btnTrack.clicked.connect(self.startClickThread)
        self.addWidget(self.btnTrack)

    def posChange(self, s):
        if len(self.inputX.text) == 0:
            self.inputX.text = 0
        elif len(self.inputY.text) == 0:
            self.inputY.text = 0

    def onMouseClick(self, x, y, pressTime, button):
        self.inputX.text = int(x)
        self.inputY.text = int(y)
        self.inputTime.text = pressTime
        buttonName = button.name.upper()
        self.comButtonType.setCurrentText(ZhButtonType[buttonName].value)

    def startClickThread(self):
        MouseUtil.listenLongPress(self.onMouseClick)

    @property
    def data(self):
        zhType = ZhButtonType(self.comButtonType.currentText())
        buttonType = ButtonType[zhType.name].value
        return {
            "type": self.type.value,
            'x': int(self.inputX.text),
            'y': int(self.inputY.text),
            'button': buttonType,
            'time': int(self.inputTime.text),
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.setData(data)
        self.inputX.text = data['x']
        self.inputY.text = data['y']
        self.comButtonType.setCurrentText(ZhButtonType[data['button'].upper()].value)
